//
//  ZBOneModel.m
//  BaseRACDemo
//
//  Created by 庄波 on 2018/3/7.
//  Copyright © 2018年 庄波. All rights reserved.
//

#import "ZBOneModel.h"
#import "ZBOneItemViewModel.h"
#import "ZBHTTPService.h"
#import "ZBHTTPService+Notice.h"
#import "ZBOneNote.h"
#import "ZBOneSubModel.h"
#import "ZBLinkmanViewModel.h"

@interface ZBOneModel ()
/// 商品数组 <MHLiveRoom *>
@property (nonatomic, readwrite, copy) NSArray *noteLists;
@end


@implementation ZBOneModel

- (void)initialize{
    [super initialize];
    self.title = @"发送";
    
    //允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    //允许上啦加载
    self.shouldPullUpToLoadMore = YES;
    ///没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    @weakify(self);
    /// 直播间列表原始数据
    
    [self.requestRemoteDataCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {

        
    }];
    
    RAC(self, noteLists) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 转模数据源
    RAC(self,dataSource) = [RACObserve(self, noteLists) map:^(NSArray * noteLists) {
        @strongify(self)
        return [self dataSourceWithLiveRooms:noteLists];
    }];
    
    /// 选中cell 跳转的命令
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath * indexPath) {
        @strongify(self);
        
//        /// 这里只是测试
//        ZBOneSubModel *viewModel = [[ZBOneSubModel alloc] initWithServices:self.services params:@{MHViewModelTitleKey:@"测试页面"}];
//        /// 执行push or present
//        [self.services pushViewModel:viewModel animated:YES];
//        return [RACSignal empty];
        
        
        ZBLinkmanViewModel *linkmanViewModel = [[ZBLinkmanViewModel alloc] initWithServices:self.services params:nil];
        [self.services pushViewModel:linkmanViewModel animated:YES];
        return [RACSignal empty];
    }];
}

/// 请求数据
- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapLiveRooms)(ZBOneNote *) = ^(ZBOneNote *products) {
        NSMutableArray *aryData = @[].mutableCopy;
        if (page == 1) {
            /// 下拉刷新
            [aryData addObjectsFromArray:products.list];
        } else {
            /// 上拉加载
            [aryData addObjectsFromArray:@[(self.noteLists ?: @[]).rac_sequence, products.list.rac_sequence].rac_sequence.flatten.array];
        }
        return aryData;
    };
    /// 请求网络数据
    return [[self.services.client  fetchLivesWithUseridx:@"6" size:self.perPage page:page] map:mapLiveRooms];
}


#pragma mark - 辅助方法
- (NSArray *)dataSourceWithLiveRooms:(NSArray *)liveRooms {
    if (MHObjectIsNil(liveRooms) || liveRooms.count == 0) return nil;
    NSArray *viewModels = [liveRooms.rac_sequence map:^(ZBOneNoteNoticeList *liveRoom) {
        ZBOneItemViewModel *viewModel = [[ZBOneItemViewModel alloc] initWithLiveRoom:liveRoom];
        return viewModel;
    }].array;
    return viewModels ?: @[] ;
}
@end
